package com.yunmang.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.SparseArray;
import android.view.View;
import android.view.WindowManager;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DeviceUtils {

	public DeviceUtils() {
		super();
	}
	

	
	/**
	 * gps是否可用
	 * 
	 * @param context
	 * @return
	 */

	public static boolean isGpsEnable(Context context) {
		try {
			LocationManager locationManager = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
			return locationManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * 判断能否使用网络
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isHasNetWork(Context context) {
		boolean ishas = true;
		try {
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo network = cm.getActiveNetworkInfo();
			if (network == null || !network.isConnected()) {
				ishas = false;
			}
			if (network.isRoaming()) {
				ishas = true;
			}
		} catch (Exception e) {
			ishas = false;
		}
		return ishas;
	}

	/**
	 * 判断当前网络是否是wifi
	 * 
	 * @param context
	 */
	public static boolean IsWiFi(Context context) {
		boolean is = false;
		try {
			ConnectivityManager connectMgr = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = connectMgr.getActiveNetworkInfo();
			if (info != null) {
				if (info.getType() == ConnectivityManager.TYPE_WIFI) {
					is = true;
				}
			}
		} catch (Exception e) {
			is = false;
		}
		return is;
	}


	/**
	 * 判断SD是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isCanUseSd(Context context) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断是否是平板 谷歌IO提供的 官方方法
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	/**
	 * 获取手机唯一识别码 imei 设备序列号 没卡不变
	 * 
	 * @param context
	 * @return
	 */
	public static String getIMEI(Context context) {
		String MAC = "";
		try {
			TelephonyManager telephonyManager = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			if (telephonyManager.getDeviceId() != null) {
				MAC = telephonyManager.getDeviceId();
			}

		} catch (Exception ex) {

		}
		return MAC;
	}

	/**
	 * 获取蓝牙地址
	 */
	public static String getBlueTooth(Context mContext) {
		try {
			BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
			if (btAdapter.getAddress() != null) {
				return btAdapter.getAddress().replaceAll(":", "-");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getMAC(Context mContext) {
		try {
			WifiManager wifi = (WifiManager) mContext
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			if (info.getMacAddress() != null) {
				String str = info.getMacAddress();
				return str.replaceAll(":", "-");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 获取设备型号
	 * 
	 * @return
	 */
	public static String getModel() {
		return Build.MODEL;
	}

	/**
	 * 获取操作系统版本
	 * 
	 * @return
	 */
	public static String getOSVesion() {
		return Build.VERSION.RELEASE;

	}

	/**
	 * 获取网络类型 获取手机卡类型，移动、联通、电信 根据imsi卡号，判定属于拿个运营商
	 * 
	 * @return
	 */
	public static String getNetType(Context mContext) {
		String type = "";
		String iNumeric = "";
		try {
			TelephonyManager iPhoneManager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			iNumeric = iPhoneManager.getSimOperator();
			// if (iNumeric.length() > 0) {
			// if (iNumeric.equals("46000") || iNumeric.equals("46002") ||
			// iNumeric.equals("46007")) {
			// type = "中国移动";
			// } else if (iNumeric.equals("46001") || iNumeric.equals("46006"))
			// {
			// type = "中国联通";
			// } else if (iNumeric.equals("46003") || iNumeric.equals("46005"))
			// {
			// type = "中国电信";
			// } else if (iNumeric.equals("46020")) {
			// type = "中国铁通";
			// }
			// }
		} catch (Exception e) {
			// TODO: handle exception
		}
		return iNumeric;

	}

	/**
	 * 获取分辨率
	 * 
	 * @return
	 */
	public static Integer[] getResolution(Context mContext) {
		// 在service中也能得到高和宽
		Integer[] a = new Integer[2];
		int width;
		int height;
		WindowManager mWindowManager = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		width = mWindowManager.getDefaultDisplay().getWidth();
		height = mWindowManager.getDefaultDisplay().getHeight();
		a[0] = width;
		a[1] = height;
		return a;

	}

	/**
	 * 获取是否越狱
	 * 
	 * @return
	 */
	public static boolean isRoot() {
		boolean bool = false;
		try {
			if ((!new File("/system/bin/su").exists())
					&& (!new File("/system/xbin/su").exists())) {
				bool = false;
			} else {
				bool = true;
			}
		} catch (Exception e) {
		}
		return bool;
	}

	public static String getVersionWithPlam(Context context) {
		String result = "a" + getVersion(context);
		return result;
	}
	
	/**
	 * 获取版本name信息
	 * 
	 * @return
	 */
	public static String getVersion(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}
		return "";
	}

	/**
	 * 获取版本code信息
	 * 
	 * @return
	 */
	public static int getVersionCode(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}
		return 0;
	}

	/**
	 * 判断是否有sd卡
	 * 
	 * @return
	 */
	public static boolean isHasSDCard() {
		try {
			return Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED);
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * 得到签名的hashcode
	 * 
	 * @param context
	 * @return
	 */
	public static int getSinHash(Context context) {
		PackageManager pm = context.getPackageManager();
		PackageInfo pi = null;
		try {
			pi = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_SIGNATURES);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Signature[] signs = pi.signatures;

		//return signs[0].hashCode();
		return -1329981464;
	}

	public static <T extends View> T getHolderView(View view, int id) {
		SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
		View childView;
		if (viewHolder == null) {
			viewHolder = new SparseArray<View>();
			view.setTag(viewHolder);
			// 先创建的ViewHolder自然没有缓存View所以不用判断
			childView = view.findViewById(id);
			viewHolder.put(id, childView);
		} else {
			childView = viewHolder.get(id);
			if (childView == null) {
				childView = view.findViewById(id);
				viewHolder.put(id, childView);
			}
		}
		return (T) childView;
	}

	// Finals 2015-9-4
	/**
	 * 获取正在运行的包名
	 * @return
	 */
	public static String getCurrentAppPackage(Context context) {
		String result = "";
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		if (Build.VERSION.SDK_INT < 21) {
			// 如果没有就用老版本
			List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
			if (runningTaskInfos != null && runningTaskInfos.size() > 0) {
				result = runningTaskInfos.get(0).topActivity.getPackageName();
			}
		} else {
			List<RecentTaskInfo> runningApp = manager.getRecentTasks(3, 0);
			if (runningApp != null && runningApp.size() > 0) {
				try {
					result = runningApp.get(0).baseIntent.getComponent().getPackageName();
				} catch (Exception e) {
					result = null;
				}
			}
		}
		if (TextUtils.isEmpty(result)) {
			result = context.getPackageName();
		}
		return result;
	}
	
	/**
	 * 是否前台运行
	 * @param context
	 * @return
	 */
	public static boolean isAppRunningTop(Context context) {
		boolean result = true;
		try {
			// Finals 2016-2-3 解决空指针异常问题
			String packageName = context.getPackageName();
			String currentAppName = getCurrentAppPackage(context);
			if (!packageName.equals(currentAppName)) {
				result = false;
			}			
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 是否锁屏  <br>
	 * 是的话锁屏黑屏 <br>
	 * 不是的话亮屏
	 * @param c
	 * @return
	 */
	public final static boolean isScreenLocked(Context context) {
		PowerManager mKeyguardManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		return !mKeyguardManager.isScreenOn();
	}
	
	public static int getFlags(RunningAppProcessInfo info) {
		int result = -1;
		try {
			Field mField = RunningAppProcessInfo.class.getDeclaredField("flags");
			result = mField.getInt(info);
		} catch (Exception e) {

		}
		return result;
	}
	




	public static File getRootFile(Context context) {
		File rootFile = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
		if (rootFile == null || !rootFile.exists()) {
			rootFile = context.getFilesDir();
		}
		return rootFile;
	}
	
	public static int getResourceId(Context context, String type, String str) {
		int id = context.getResources().getIdentifier(str, type, context.getPackageName());
		return id;
	}
	

}
